﻿using ExcelDataReader;
using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace SheetDirCp
{
    class Program
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static List<CopyRule> lstCopyRules = new List<CopyRule>();
        static void Copy(string src, string desDir)
        {
            log.Info($"正在处理{src}");
            try
            {
                if (!Directory.Exists(desDir))
                    Directory.CreateDirectory(desDir);

                string des = Path.Combine(desDir, Path.GetFileName(src));
                if (!File.Exists(des))
                {
                    File.Copy(src, des, false);
                    Console.WriteLine($"已复制到{des}");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }

        }


        static void Main(string[] args)
        {
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            XmlConfigurator.ConfigureAndWatch(logRepository, new FileInfo("SheetDirCp.dll.config"));
            if (!Directory.Exists("结果"))
                Directory.CreateDirectory("结果");


            DataTable dt = ReadExcel();
            log.Info($"共读到excel{dt.Rows.Count}行数据\n");
            foreach (DataRow r in dt.Rows)
            {
                if (r[0] == null || r[1] == null || r[2] == null)
                    continue;
                string id = r[0].ToString();
                string dir = r[1].ToString();
                string fnw = r[2].ToString();
                if (id == "序号" || string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(dir) || string.IsNullOrWhiteSpace(fnw))
                    continue;
                lstCopyRules.Add(new CopyRule(id, dir, fnw));
                //Console.WriteLine($"{r[0]}\t{r[1]}\t{r[2]}");

            }
            var lstRealFiles = Directory.GetFiles(Environment.CurrentDirectory, "*.jpg").ToList();
            var lstRealFilesW = lstRealFiles.Select(x => Path.GetFileNameWithoutExtension(x)).ToList();
            File.WriteAllLines("结果/ID对应文件不存在.txt", lstCopyRules.Where(x =>
            !lstRealFilesW.Any(y => y == x.File)).Select(x => x.Id).ToList());
            var lstRealFilesNoRule = lstRealFilesW.Where(x =>
!lstCopyRules.Any(y => y.File == x)).ToList();
            File.WriteAllLines("结果/存在的文件但不存在表格.txt", lstRealFilesNoRule);
            var allDefinedFileNameNoExts = lstCopyRules.Select(x => x.File);
            foreach (string filename in lstRealFiles)
            {
                string fnw = Path.GetFileNameWithoutExtension(filename);

                foreach (string dir in lstCopyRules.Where(x => x.File == fnw).Select(x => x.Dir))
                {
                    Copy(filename, $"结果/{dir}");
                }
                if (!allDefinedFileNameNoExts.Any(x => x == fnw))
                {
                    Copy(filename, $"结果/文件存在但excel没定义");
                }
            }

            log.Info("运行结束！");
            Console.WriteLine("运行结束！");
            Console.ReadKey();
        }

        static DataTable ReadExcel()
        {
            using (var stream = File.Open("数据表格.xlsx", FileMode.Open, FileAccess.Read))
            {
                // Auto-detect format, supports:
                //  - Binary Excel files (2.0-2003 format; *.xls)
                //  - OpenXml Excel files (2007 format; *.xlsx, *.xlsb)
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    // Choose one of either 1 or 2:

                    // 1. Use the reader methods
                    do
                    {
                        while (reader.Read())
                        {
                            // reader.GetDouble(0);
                        }
                    } while (reader.NextResult());

                    // 2. Use the AsDataSet extension method
                    var result = reader.AsDataSet();

                    // The result of each spreadsheet is in result.Tables
                    Console.WriteLine(result.Tables.Count);
                    return result.Tables[0];
                }
            }
        }
    }
}
